<template>
  <el-card v-loading="isLoading">
    <template #header>
      <div class="card-header">
        <div class="card-header-title">
          <el-icon><MoonNight /></el-icon>
          <span>见习夜班申报</span>
        </div>
        <el-alert
          :type="
            exceptions.length > 0
              ? 'error'
              : warnings.length > 0
              ? 'warning'
              : 'success'
          "
          :closable="false"
        >
          <!-- <el-text type="info"> -->
          <ul style="padding-left: 1em">
            <li>此页面用于见习人员后半夜期间无教员时提交夜班申报</li>
            <li>仅在每天02:30至07:30允许两名见习人员提交夜班申报</li>
            <li v-if="!commonStore.isReal">演示模式</li>
          </ul>
          <!-- </el-text> -->
        </el-alert>
      </div>
    </template>
    <template #default>
      <div class="card-body">
        <el-alert
          v-for="item in exceptions"
          :type="item.type"
          :closable="false"
          show-icon
          :title="item.message"
        />
        <el-alert
          v-for="item in warnings"
          :type="item.type"
          :closable="false"
          show-icon
          :title="item.message"
        />
        <el-form label-width="90px">
          <el-form-item label="见习人员">
            <el-select v-model="selectedNoviciateIndex" style="width: 100%">
              <el-option
                v-for="(user, idx) in noviciateList"
                :value="idx"
                :label="user.name"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="开始时间">
            <el-input
              v-model="startTime"
              :prefix-icon="Clock"
              disabled
              style="width: 100%"
            />
          </el-form-item>
          <el-form-item label="结束时间">
            <el-input
              v-model="endTime"
              :prefix-icon="Clock"
              disabled
              style="width: 100%"
            />
          </el-form-item>
          <el-form-item label="证明人">
            <el-select v-model="selectedWitnessIndex" style="width: 100%">
              <el-option
                v-for="(user, idx) in witnessList"
                :value="idx"
                :label="user.name"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-form>
      </div>
    </template>
    <template #footer>
      <div class="card-footer">
        <el-button
          type="primary"
          :disabled="exceptions.length > 0 || !(isAvailable && isValid)"
          @click="submit()"
        >
          <!-- <el-icon><Refresh /></el-icon> -->
          <el-icon><Pointer /></el-icon>
          <span>提交</span>
        </el-button>
        <el-button
          type="info"
          link
          v-if="!(commonStore.isReal && isAvailable)"
          @click="loadNoviciates"
        >
          <span>重置</span>
        </el-button>
      </div>
    </template>
  </el-card>
</template>

<script setup>
import { ref, computed, onMounted } from "vue";
import { Clock } from "@element-plus/icons-vue";
import { ElMessageBox } from "element-plus";
import axios from "axios";
import dayjs from "dayjs";
import useSeatStore from "@/store/seat.js";
import useCommonStore from "@/store/common.js";

const seatStore = useSeatStore();
const commonStore = useCommonStore();

const selectedNoviciateIndex = ref(-1);
const selectedWitnessIndex = ref(-1);
const startTime = ref("");
const endTime = ref("");
const noviciateList = ref([]);
const witnessList = ref([]);
const isLoading = ref(false);
const queryStart = ref("");
const queryEnd = ref("");
const existedRecoed = ref([]);
const remark = ref("见习夜班申报");

const exceptions = computed(() => {
  let result = new Array();
  if (isLoading.value) {
    result.push({ type: "info", message: "正在读取数据……" });
    return result;
  }
  if (commonStore.isReal) {
    let now = dayjs();
    let date = now.format("YYYY-MM-DD");
    if (
      !(
        now.isSameOrAfter(date + " 02:30:00") &&
        now.isSameOrBefore(date + " 07:30:00")
      )
    ) {
      result.push({ type: "error", message: "当前不在有效时段！" });
    }
  }
  if (existedRecoed.value.length > 1) {
    result.push({
      type: "error",
      message: `已存在 ${existedRecoed.value[0].userName} 和 ${existedRecoed.value[1].userName} 的今日夜班申报记录！`,
    });
  }
  if (noviciateList.value.length == 0) {
    result.push({
      type: "error",
      message: "未找到昨日有打卡记录的见习人员！",
    });
  }
  if (witnessList.value.length == 0) {
    result.push({
      type: "error",
      message: "未找到代班主任岗打卡记录！",
    });
  }
  return result;
});

const isAvailable = computed(() => {
  return exceptions.value.length == 0;
});

const warnings = computed(() => {
  let result = new Array();
  if (exceptions.value.length > 0) {
    return result;
  }
  if (selectedNoviciateIndex.value == null) {
    result.push({
      type: "warning",
      message: "请选择见习人员",
    });
  }
  if (selectedWitnessIndex.value == null) {
    result.push({
      type: "warning",
      message: "请选择证明人",
    });
  }
  return result;
});

const isValid = computed(() => warnings.value.length == 0);

const selectedNoviciate = computed(() =>
  isAvailable.value ? noviciateList.value[selectedNoviciateIndex.value] : null
);
const selectedWitness = computed(() =>
  isAvailable.value ? witnessList.value[selectedWitnessIndex.value] : null
);

const setDefaultTime = () => {
  let fakeDate = "2024-05-01 00:00:00";
  let targetDayjs = commonStore.isReal ? dayjs() : dayjs(fakeDate);
  startTime.value = targetDayjs
    .hour(3)
    .minute(0)
    .second(0)
    .format("YYYY-MM-DD HH:mm:ss");
  endTime.value = targetDayjs
    .hour(7)
    .minute(0)
    .second(0)
    .format("YYYY-MM-DD HH:mm:ss");
  queryStart.value = targetDayjs
    .subtract(1, "day")
    .hour(10)
    .minute(0)
    .format("YYYY-MM-DD HH:mm:ss");
  queryEnd.value = targetDayjs
    .subtract(1, "day")
    .hour(23)
    .minute(0)
    .format("YYYY-MM-DD HH:mm:ss");
};

const matchWitness = () => {
  let sups = seatStore.seatStatusFull.filter(
    (cell) =>
      cell.orgGroup == "TMA" &&
      (cell.seatName == "SUP01" || cell.seatName == "SUP02") &&
      cell.users.length > 0
  );
  if (sups.length > 0 && sups[0].users[0].userId) {
    let witnesses = new Array();
    sups.forEach((s) => {
      s.users.forEach((u) => {
        witnesses.push({
          name: u.userName,
          uid: u.userId,
        });
      });
    });
    witnessList.value = witnesses;
    let witnesUser = sups[0].users[0];
    // witness.value = witnesUser.userId;
    selectedWitnessIndex.value = 0;
    console.log("NoviciateNightWork", "witnesUser", witnesUser);
  } else {
    selectedWitnessIndex.value = null;
    console.error("NoviciateNightWork", "witnesUser", seatStore.seatStatusFull);
  }
};

const loadNoviciates = () => {
  let noviciates = new Array();
  return new Promise((resolve, reject) => {
    axios
      .post("api/seat_hours_get.php", {
        start: queryStart.value,
        end: queryEnd.value,
      })
      .then((response) => {
        let records = response.data.content.filter(
          (rec) => rec.seatRoleId == 3
        );

        records.forEach((rec) => {
          if (noviciates.filter((user) => user.uid == rec.userId).length == 0) {
            noviciates.push({
              name: rec.userName,
              uid: rec.userId,
              orgId: rec.orgId,
            });
          }
        });
        noviciateList.value = noviciates;
        selectedNoviciateIndex.value = null;
        console.log("NoviciateNightWork", "loadNoviciates", noviciates);
        resolve(noviciates);
      })
      .catch((error) => {
        console.error("NoviciateNightWork", "loadNoviciates", error);
        reject(error);
      });
  });
};

const findExistedRecord = () => {
  return new Promise((resolve, reject) => {
    axios
      .post("api/seat_hours_declaration.php", {
        method: "GET",
        startTime: startTime.value,
        endTime: endTime.value,
        filters: [{ field: "remark", value: remark.value }],
      })
      .then((response) => {
        let existed = response.data.content;
        if (existed.length > 0) {
          for (let i = 0; i < noviciateList.value.length; i++) {
            if (existed[0].userId == noviciateList.value[i].uid) {
              selectedNoviciateIndex.value = i;
            }
          }
        }
        existedRecoed.value = existed;
        console.log("NoviciateNightWork", "findExistedRecord", response.data);
        resolve(response.data);
      })
      .catch((error) => {
        console.error("NoviciateNightWork", "findExistedRecord", error);
        reject(error);
      });
  });
};

const submit = () => {
  let payload = {
    method: "SET",
    data: [
      {
        userName: selectedNoviciate.value.name,
        userId: selectedNoviciate.value.uid,
        orgId: selectedNoviciate.value.orgId,
        startTime: startTime.value,
        endTime: endTime.value,
        seatCode: "TM01",
        seatRole: "见习",
        seatRoleId: 3,
        seatPost: "协调",
        seatPostId: 2,
        witnessId: selectedWitness.value.uid,
        witnessName: selectedWitness.value.name,
        asHour: 0,
        remark: remark.value,
      },
    ],
  };
  console.log("NoviciateNightWork", "submitPayload", payload);
  return new Promise((resolve, reject) => {
    ElMessageBox.confirm("提交后不可撤销，确认信息填写正确吗", "确认", {
      confirmButtonText: "提交",
      cancelButtonText: "取消",
      type: "warning",
    })
      .then(() => {
        isLoading.value = true;
        axios
          .post("api/seat_hours_declaration.php", payload)
          .then((response) => {
            isLoading.value = false;
            if (response.data.success) {
              ElMessageBox.alert(
                `${selectedNoviciate.value.name}(${startTime.value}至${endTime.value})`,
                "已提交",
                {
                  confirmButtonText: "OK",
                  callback: () => {
                    reset();
                  },
                }
              );
            } else {
              ElMessageBox.alert(response.data.failed, "出错了", {
                confirmButtonText: "OK",
                callback: () => {},
              });
            }
            console.log("NoviciateNightWork", "submitResponse", response.data);
            resolve(response.data);
          })
          .catch((error) => {
            isLoading.value = false;
            ElMessageBox.alert(JSON.stringify(error, null, 2), "出错了", {
              confirmButtonText: "OK",
              callback: () => {},
            });
            console.error("NoviciateNightWork", "submitError", error);
            reject(error);
          });
      })
      .catch(() => {
        resolve(null);
      });
  });
};

const reset = () => {
  isLoading.value = true;
  setDefaultTime();
  loadNoviciates()
    .then(() => {
      findExistedRecord()
        .then(() => {
          matchWitness();
          isLoading.value = false;
        })
        .catch(() => {
          isLoading.value = false;
        });
    })
    .catch(() => {
      isLoading.value = false;
    });
};

onMounted(() => {
  reset();
});
</script>

<style scoped>
.card-header {
  width: 100%;
  /* max-width: 480px; */
}

.card-header > *:not(:first-child) {
  margin-top: 1em;
}

.card-header-title {
  font-size: 1.25em;
  font-weight: bolder;
  display: flex;
  align-items: center;
}

.card-header-title > *:not(:first-child) {
  margin-left: 0.5em;
}

.card-body {
  width: 100%;
  /* max-width: 480px; */
}

.card-body > *:not(:first-child) {
  margin-top: 1em;
}

.card-footer {
  display: flex;
  align-items: center;
  justify-content: center;
  margin: 12px 0;
}
</style>
